import 'dart:io';

import 'package:file_transfer/model/message_model.dart';
import 'package:file_transfer/model/simple_model.dart';
import 'package:file_transfer/pojo/channel_message.dart';
import 'package:file_transfer/utils/svg_util.dart';
import 'package:file_transfer/utils/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:open_file/open_file.dart';
import 'package:provider/provider.dart';


class SystemMessageWidget extends StatelessWidget {
  final SystemMessage message;
  const SystemMessageWidget(this.message,{super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 15),
      padding: const EdgeInsets.only(left: 15,right: 15,top: 5,bottom: 5),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(360),
          color: const Color(0x332D2D2D)
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text("与 ${message.name} 建立连接失败，查看 ",style: const TextStyle(
              fontSize: 13,
              color: Colors.white
          )),
          GestureDetector(
            onTap: ()=>ToastUtil.show("重新尝试连接，或者更换移动热点，确保设备在同一个局域网中"),
            child: const Text("解决方案",style: TextStyle(
                fontSize: 13,
                color: Color(0xff007AFF)
            ),),
          )
        ],
      ),
    );
  }
}


class TextMessageWidget extends StatelessWidget {

  final TextChannelMessage message;
  const TextMessageWidget(this.message,{super.key});

  @override
  Widget build(BuildContext context) {
    if(message.local){
      return Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Container(
              margin: const EdgeInsets.only(left: 130, right: 20, top: 15),
              padding: const EdgeInsets.all(8.0),
              decoration: BoxDecoration(
                  color: const Color(0xff007aff),
                  borderRadius: BorderRadius.circular(8.0)),
              child: Text(message.text,style: const TextStyle(
                fontSize: 20,
                color: Colors.white
              ),)),
        ],
      );
    }else{
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
              margin: const EdgeInsets.only(left: 20,top: 15),
              child: Text("${message.user?.name}:",style: const TextStyle(color: Color(0xffB0B0B0)),)),
          Container(
              margin: const EdgeInsets.only(right: 130, left: 20, bottom: 15,top: 5),
              padding: const EdgeInsets.all(8.0),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.0)),
              child: Text(message.text,style: const TextStyle(color: Colors.black,fontSize: 20),)),
        ],
      );
    }
  }
}

class FileMessageWidget extends StatelessWidget {
  final FileChannelMessage message;
  const FileMessageWidget(this.message,{super.key});

  @override
  Widget build(BuildContext context) {
    if(message.local){
      return SendFileWidget(message);
    }else{
      return ReceiveFileWidget(message);
    }
  }
}


class SendFileWidget extends StatefulWidget {
  final FileChannelMessage message;
  const SendFileWidget(this.message,{super.key});

  @override
  State<SendFileWidget> createState() => _SendFileWidgetState();
}

class _SendFileWidgetState extends State<SendFileWidget> {


  Widget _progressText(){
    final messageModel = context.watch<MessageModel>();
    final selected = messageModel.sendingFile == widget.message;
    const style = TextStyle(
        color: Color(0xff509686),
        fontSize: 15,
        fontWeight: FontWeight.bold
    );
    return selected ?Selector<MessageModel,int>(builder: (BuildContext context, int value, Widget? child) {
      return value/widget.message.size >= 0.99 ? const Text("已发送",style: style) : Text("(${(value/widget.message.size*100).toStringAsFixed(2)})%",style: style);
      // return Text("(${(value/widget.message.size*100).toStringAsFixed(2)})%",style: style);
    }, selector: (_ , MessageModel messageModel) => messageModel.sendFileProgress)
        :const Text("已发送",style: style);
  }

  @override
  Widget build(BuildContext context) {
    final w = MediaQuery.sizeOf(context).width * 1.5 / 5;
    final size = widget.message.size/1024;
    String fileSize;
    if(size >= 1024){
      fileSize = "${(size/1024).toStringAsFixed(2)}MB";
    }else{
      fileSize = "${size.toStringAsFixed(2)}KB";
    }
    return Container(
      height: 100,
      margin:  EdgeInsets.only(top: 15,right: 20,left: w),
      padding: const EdgeInsets.only(top: 8,bottom: 8,left: 16,right: 16),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(15.0),
          color: Colors.white
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(widget.message.name,style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20,
                    overflow: TextOverflow.ellipsis
                ),),
                const SizedBox(height: 20),
                Row(
                  children: [
                    Text(fileSize,
                      style: const TextStyle(
                        color: Color(0xff707070),
                        fontSize: 14,
                      ),),
                    const SizedBox(width: 10),
                    _progressText()
                  ],
                )
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
               /* border: Border.all(
                    color: Colors.black
                ),*/
                color: Colors.white
            ),
            height: 50,width: 50,
            child: SvgPicture.asset(SvgUtil.fileSvg),
          )
        ],
      ),
    );
  }
}

class ReceiveFileWidget extends StatefulWidget {
  final FileChannelMessage message;
  const ReceiveFileWidget(this.message,{super.key});

  @override
  State<ReceiveFileWidget> createState() => _ReceiveFileWidgetState();
}

class _ReceiveFileWidgetState extends State<ReceiveFileWidget> {


  Widget _progressText(){
    final messageModel = context.watch<MessageModel>();
    final selected = messageModel.receivingFile == widget.message;
    const style = TextStyle(
        color: Color(0xff509686),
        fontSize: 15,
        fontWeight: FontWeight.bold
    );
    return selected ?Selector<MessageModel,int>(builder: (BuildContext context, int value, Widget? child) {
      return value/widget.message.size >= 0.99 ? const Text("已接收",style: style) : Text("(${(value/widget.message.size*100).toStringAsFixed(2)})%",style: style);
      // return Text("(${(value/widget.message.size*100).toStringAsFixed(2)})%",style: style);
    }, selector: (_ , MessageModel messageModel) => messageModel.receiveFileProgress)
        :const Text("已接收",style: style);
  }

  openFile() async {
    final messageModel = context.read<MessageModel>();
    final selected = messageModel.receivingFile == widget.message;
    if(!selected || messageModel.receiveFileProgress >= widget.message.size){
      final simpleModel = context.read<SimpleModel>();
      final path = "${simpleModel.receiveDirectoryPath}/${widget.message.name}";
      if (!File(path).existsSync()){
        ToastUtil.show("文件已被删除！！",backgroundColor: Colors.yellow,textColor: Colors.white);
        return;
      }
      await OpenFile.open(path);
    }
  }

  @override
  Widget build(BuildContext context) {
    final w = MediaQuery.sizeOf(context).width * 1.5 / 5;
    final size = widget.message.size/1024;
    String fileSize;
    if(size >= 1024){
      fileSize = "${(size/1024).toStringAsFixed(2)}MB";
    }else{
      fileSize = "${size.toStringAsFixed(2)}KB";
    }
    return InkWell(
      onTap: openFile,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
              margin: const EdgeInsets.only(left: 20,top: 15),
              child: Text("${widget.message.user?.name}:",style: const TextStyle(color: Color(0xffB0B0B0)),)),
          Container(
            height: 100,
            margin:  EdgeInsets.only(top: 5,left: 20,right: w),
            padding: const EdgeInsets.only(top: 8,bottom: 8,left: 16,right: 16),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15.0),
                color: Colors.white
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(widget.message.name,style: const TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 20,
                          overflow: TextOverflow.ellipsis
                      ),),
                      const SizedBox(height: 20),
                      Row(
                        children: [
                          Text(fileSize,
                            style: const TextStyle(
                              color: Color(0xff707070),
                              fontSize: 14,
                            ),),
                          const SizedBox(width: 10),
                          _progressText()
                        ],
                      )
                    ],
                  ),
                ),
                Container(
                  decoration: BoxDecoration(
                      /*border: Border.all(
                          color: Colors.black
                      ),*/
                      color: Colors.white
                  ),
                  height: 50,width: 50,
                  child: SvgPicture.asset(SvgUtil.fileSvg),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }
}

